package dbx

import (
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/datax/mapx"
)

// 删除数据模型内部的集合的键
func (delayQueue *DelayQueue) DictReplace(dictItem IDBDictItem, data map[string]interface{}, configs ...*Config) {
	if delayQueue.isExpired {
		panic("delay is expired")
	}
	path := dictItem.DBPath()
	if string(path[0]) != "/" {
		panic("路径的首字符必须为/")
	}
	key := dictItem.DBIdent()
	model := dictItem.DBModel()
	delayItem := delayQueue.getOrNewItem(model)
	switch delayItem.Opt {
	case Opt_删除:
		panic("文档已经被删除")
	case Opt_修改:
	case Opt_创建:
	default:
		delayItem.Opt = Opt_修改
	}
	conf := getConfig(configs)
	if conf == nil || !conf.EnableNil {
		data = mapx.FilterMapNotNil(data)
	}

	delayItem.addOptItem(&OptItem{
		Opt:  DictOpt_替换,
		Path: path + "/" + key,
		Data: data,
	})

	dictObject := dictItem.DBObject()
	delayQueue.updateOriginItem(path+"/"+key, dictObject, nil)

	dictObject.RefSetNil()
	dictObject.RefUpdate(data)
}

// 不存在才能创建
// 注意这里不会检查字段中，是否存在对象, 使用的时候要注意
// 在数据库文档的集合中创建
// 在数据库文档的集合中创建，并保存到[dbset]字典对象中
func (delayQueue *DelayQueue) DictReplaceField(dictItem IDBDictItem, fieldPath string, data map[string]interface{}, configs ...*Config) {
	if delayQueue.isExpired {
		panic("delay is expired")
	}
	if fieldPath == "/" {
		panic("不支持替换字典项自身")
	}
	if string(fieldPath[0]) != "/" {
		panic("路径的首字符必须为/")
	}

	dictpath := dictItem.DBPath()
	ident := dictItem.DBIdent()
	model := dictItem.DBModel()
	dictObject := dictItem.DBObject()
	delayItem := delayQueue.getOrNewItem(model)
	switch delayItem.Opt {
	case Opt_删除:
		panic("文档已经被删除")
	case Opt_修改:
	case Opt_创建:
	default:
		delayItem.Opt = Opt_修改
	}

	conf := getConfig(configs)
	if conf == nil || !conf.EnableNil {
		data = mapx.FilterMapNotNil(data)
	}

	delayItem.addOptItem(&OptItem{
		Opt:   DictOpt_创建,
		Path:  dictpath + "/" + ident + fieldPath,
		Field: "",
		Data:  data,
	})

	updateMap := datax.M{}
	mapx.SetByPath(updateMap, fieldPath, nil)
	delayQueue.updateOriginItem(dictpath+"/"+ident, dictObject, updateMap)
	dictObject.RefReplaceObjectByPath(fieldPath, data)
}

// 被标记的文档的路径会被替换
// !!!慎用，上线前必须确保不会丢失数据
func (delayQueue *DelayQueue) Replace(model IDBModelDelay, fieldPath string, data datax.M) {
	if delayQueue.isExpired {
		panic("delay is expired")
	}
	if fieldPath == "/" {
		panic("不支持替换字典项自身")
	}
	if string(fieldPath[0]) != "/" {
		panic("路径的首字符必须为/")
	}

	delayItem := delayQueue.getOrNewItem(model)
	switch delayItem.Opt {
	case Opt_删除:
		panic("文档已经被删除")
	case Opt_修改:
	case Opt_创建:
	default:
		delayItem.Opt = Opt_修改
	}

	delayItem.addOptItem(&OptItem{
		Opt:   DictOpt_创建,
		Path:  fieldPath,
		Field: "",
		Data:  data,
	})

	updateMap := datax.M{}
	mapx.SetByPath(updateMap, fieldPath, nil)
	delayQueue.updateOriginItem(fieldPath, model, updateMap)
	model.RefReplaceObjectByPath(fieldPath, data)
}
